// Copyright (c) 2006, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//
// Author: arvin.chen
//
//

#ifndef ALGORITHM_SORT_COUNTOPTIMIZE_H_
#define ALGORITHM_SORT_COUNTOPTIMIZE_H_
#include <stack>

#ifndef ALGORITHM_SORT_BASE_H_
#include "algorithm/sort/base.h"
#endif

namespace algorithm {
	namespace sort {
		
		//only support int
		class CountOptimize : public Base<int> {
		public:

			/**
			* Construction
			*
			* @param
			* @return
			*/
			CountOptimize() :
				Base<int>::Base(kCountOptimize)
			{
				
			}

			/**
			* Destruction
			*
			* @param VOID
			* @return
			*/
			~CountOptimize()
			{

			}

			/**
			* sort
			*
			* @param int arr[]
			* @param int len
			* @return int
			*/
			virtual int* sort(int arr[], int len)
			{
				if (nullptr == arr || 1 >= len) return arr;
				int min = arr[0];
				int max = arr[0];
				// Find the maximum and minimum values of the array
				for (int i = 1; i < len; i++) {
					if (max < arr[i])
						max = arr[i];
					if (min > arr[i])
						min = arr[i];
				}
				int d = max - min + 1;
				//Create a temporary array of size max
				//std::vector<int> temp(d);
				int *temp = new int[d];
				memset(temp, 0x00, sizeof(int) * d);
				//CountOptimize the number of occurrences of element i
				for (int i = 0; i < len; i++) {
					temp[arr[i] - min]++;
				}
				int k = 0;
				//Summarize the statistics of the temporary array to the original array
				for (int i = 0; i < d; i++) {
					for (int j = temp[i]; j > 0; j--) {
						arr[k++] = i + min;
					}
				}
				delete[] temp;
				temp = nullptr;
				return arr;
			}

		protected:
			/**
			* Assignment
			*
			* @param const CountOptimize& cbase
			* @return CountOptimize&
			*/
			CountOptimize& operator=(const CountOptimize& cbase);

			/**
			* Copy Construction
			*
			* @param const CountOptimize& cbase
			* @return
			*/
			CountOptimize(const CountOptimize& cbase);

		private:

		public:
		protected:
		private:

		};
	} // namespace algorithm 
} // namespace sort


#endif  // ALGORITHM_SORT_COUNTOPTIMIZE_H_
